package com.godme.rabbitmq.controller;


import com.alibaba.fastjson.JSON;
import com.godme.rabbitmq.bean.Order;
import com.godme.rabbitmq.props.RabbitProperties;
import com.godme.rabbitmq.repo.OrderRepository;
import com.godme.rabbitmq.repo.ProductRepository;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/shopping")
public class ShoppingController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    RabbitProperties rabbitProperties;


    @GetMapping("/order")
    public String order(Model model, @RequestParam("productId") String productId){
        productRepository.changeResidue(productId, -1);

        Order order = new Order();
        order.setStatus("待支付");
        order.setPid(productId);
        orderRepository.insertOrder(order);
        rabbitTemplate.convertAndSend(rabbitProperties.getOrderExchange(), rabbitProperties.getOrderRoutingKey(),
                JSON.toJSONString(order), message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setExpiration("10000");
                    return message;
                });
        model.addAttribute("orders", orderRepository.findAll());
        return "orders";
    }


    @GetMapping("/list")
    public ModelAndView list(){
        return new ModelAndView("orders", "orders", orderRepository.findAll());
    }

    @GetMapping("/pay")
    public String pay(Model model, String orderId){
        rabbitTemplate.receive(rabbitProperties.getOrderQueue());


        Order order = orderRepository.findById(orderId);
        order.setStatus("已支付");
        model.addAttribute("orders", orderRepository.findAll());
        return "orders";
    }
}
